import concurrent.futures
from typing import List, Tuple, Dict
import pandas as pd
from config import settings
from core.vocab_processor import VocabularyProcessor
from utils.logger import VocabLogger

class ChapterProcessor:
    def __init__(self, known_words: set):
        self.known_words = known_words
        self.processor = VocabularyProcessor()

    def process_chapter(self, chapter: Tuple[str, str]) -> Tuple[str, pd.DataFrame]:
        title, text = chapter
        vocab = self.processor.process_book(text, self.known_words)
        if not vocab:
            return None
        return (title, pd.DataFrame({
            '单词': vocab,
            '出现次数': [vocab.count(w) for w in vocab]
        }))

class ParallelProcessor:
    def __init__(self, known_words: set, max_workers=4):
        self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers)
        self.chapter_processor = ChapterProcessor(known_words)

    def process_chapters(self, chapters: List[Tuple[str, str]], selected_chapters: set) -> Dict[str, pd.DataFrame]:
        futures = []
        results = {}

        # 提交任务时过滤指定章节
        for idx, chapter in enumerate(chapters, 1):
            chap_title, _ = chapter
            if self._is_selected(chap_title, idx, selected_chapters):
                futures.append(self.executor.submit(
                    self.chapter_processor.process_chapter, chapter
                ))

        # 收集结果
        for future in concurrent.futures.as_completed(futures):
            result = future.result()
            if result:
                title, df = result
                results[title] = df
        return results

    def _process_chapter(self, title: str, text: str) -> Tuple[str, pd.DataFrame]:
        """确保始终返回 (title, DataFrame) 结构"""
        try:
            processor = VocabularyProcessor()
            processor.build_context_cache(text)
            vocab = processor.process_text(text, self.known_words)
            df = pd.DataFrame({
                '单词': [v[0] for v in vocab],
                '出现次数': [v[1] for v in vocab],
                '例句': [v[2] for v in vocab]
            })
            return title, df.sort_values('出现次数', ascending=False)
        except Exception as e:
            # 返回空DataFrame保持结构
            empty_df = pd.DataFrame(columns=['单词', '出现次数', '例句'])
            return title, empty_df

    def _is_selected(self, title: str, index: int, selected: set) -> bool:
        """检查章节是否在指定范围内"""
        if not selected:
            return True
        return index in selected or title in selected